import asyncio, datetime
from db import RolesDB
from controllers.login_role_controller import LoginRoleController

class BaseController:
  def __init__(self, task_list, ws_client):
    self.task_list = task_list
    self.ws_client = ws_client
    self.cur_role = None
    self.extra_data = {}
    
  def set_extra_data(self, extra_data):
    self.extra_data = extra_data

  async def auto_craft(self, extra_data={}):
    start_idx = extra_data.get("start_idx", 0)
    loop_roles = extra_data.get("loop_roles", [])
    limit = extra_data.get("limit", 0)
    db_role_list = await RolesDB.all()
    if len(loop_roles) > 0:
      db_role_list = await RolesDB.filter(role_name__in=loop_roles)
    role_list = [role.role_name for role in db_role_list]
    all_role_names = ",".join(role_list)
    await self.log(f"auto_order func start, {all_role_names}")
    role_index = start_idx
    max_idx = len(role_list) if limit == 0 else start_idx + limit
    while role_index < max_idx:
      log_prefix = self.get_log_prefix(total=limit or len(role_list), role_name=role_list[role_index], role_index=role_index)
      start_time = datetime.datetime.now()
      await self.log("auto_craft loop start", log_prefix=log_prefix)
      await asyncio.sleep(1)
      self.cur_role = db_role_list[role_index]
      await LoginRoleController(
        role_name=role_list[role_index], 
        extra_actions=self.extra_actions,
        ws_client=self.ws_client,
        log_prefix=log_prefix,
        ).start()
      time_diff = datetime.datetime.now() - start_time
      await self.log(f"总耗时 {time_diff}", log_prefix=log_prefix, message_type=2)
      role_index += 1
    await self.log("all auto_craft done!", log_prefix=log_prefix)
      
  def get_log_prefix(self, total=0, role_name="", role_index=0):
    log_prefix = f"role {role_name}, index {role_index}, total {total}"
    return log_prefix
      
  async def log(self, message_content, message_type=1, log_prefix=""):
    await self.ws_client.broadcast_log(message_content=f"{log_prefix} {message_content}", message_type=message_type)

  async def start(self, extra_data={}):
    self.extra_data = extra_data
    """ 启动所有定时任务 """
    await self.log("AutoCraftController Start")
    await self.stop_all_task()  # 停止之前所有任务
    task = asyncio.create_task(self.auto_craft(extra_data=extra_data))
    self.add_task(task)
  
  async def stop_all_task(self):
    if len(self.task_list):
      for task in self.task_list:
        try:
          task.cancel()  # 取消任务
          await task  # 等待任务停止
        except asyncio.CancelledError:
          pass  # 任务被取消时，不需要处理异常
    self.task_list.clear()  # 清空任务列表

  def add_task(self, task):
    self.task_list.append(task)

  async def stop(self):
    """ 停止定时器 """
    await self.stop_all_task()  # 停止所有任务